/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.systop.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.systop.entity.CaptchaEntity;
import com.systop.constant.AuthServiceConstant;
import com.systop.dao.CaptchaDao;
import com.systop.exception.RRException;
import com.systop.service.CaptchaService;
import com.systop.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * 验证码
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("captchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaDao, CaptchaEntity> implements CaptchaService {
    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        //将验证码内容存放到redis中
        redisUtil.set(AuthServiceConstant.PIC_VERIFY_CODE+uuid,code,60);
        //返回图片验证码
        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        //获取验证码
        String picCaptcha = String.valueOf(redisUtil.get(AuthServiceConstant.PIC_VERIFY_CODE+uuid));
        if (StringUtils.isEmpty(picCaptcha)){
            return false;
        }

        //删除使用后的验证码
        // redisUtil.del(AuthServiceConstant.PIC_VERIFY_CODE+uuid);
        redisUtil.del(AuthServiceConstant.PIC_VERIFY_CODE + uuid);

        //判断缓存中的验证码与用户输入的验证码是否相等
        if (code.equalsIgnoreCase(picCaptcha)) {
            return true;
        }
        return false;
    }

}
